import router, { constantRoutes, myrouter, resetRouter} from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken, getUserInfo, removeToken, setUserInfo,} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {getInfo} from "@/api/user";
import Layout from "@/layout/index.vue";

NProgress.configure({ showSpinner: true })

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

function filter() {

}

router.beforeEach(async(to, from, next) => {
  console.log(to);
  if (to.query.ngrogress && to.query.ngrogress === 1) {
  } else {
    // start progress bar
    NProgress.start()
  }
  // set page title
  document.title = getPageTitle(to.meta.title)
  to.meta.refresh = false;

  // determine whether the user has logged in
  const hasToken = getToken()
  if(to.path === '/receipt') {
    next();
    // NProgress.done()
  } else if (hasToken) {
    if (!getUserInfo()) {
      let res;
      try {
        res = await getInfo(hasToken);
      } catch (e) {
        removeToken();
        resetRouter();
        // NProgress.done()
        next(`/login?redirect=${to.path}`);
      }

      if (res.data.code === -1 || !res.data.data) {
        removeToken();
        resetRouter();
        next(`/login?redirect=${to.path}`);
      } else {
        router.options.routes = [...constantRoutes, ...myrouter];
        router.addRoutes(myrouter);
        // store.commit('permission/setRoutes', myrouter)
        setUserInfo(res.data.data);
        next({...to,  })
      }
    }

    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
    // NProgress.done()
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
    // NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
